﻿using AutoMapper;
using MediatR;
using Provenance.Domain.User;
using Provenance.ErrorCount;
using Provenance.Infra;
using Provenance.Infra.Interfaces.User;
using Provenance.Write.Api.Application.Command.User;

namespace Provenance.Write.Api.Application.CommandHandler.User
{
    public class DeletePermissionCommandHandler : IRequestHandler<DeletePermissionCommand, ApiResult>
    {
        private readonly IPermissionRepository _permissionRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly ILogger<DeletePermissionCommandHandler> _logger;
        private readonly IMapper _mapper;
        private readonly ProvenanceDbContext _dbContext;
        public DeletePermissionCommandHandler(IPermissionRepository permissionRepository, ILogger<DeletePermissionCommandHandler> logger, IMapper mapper, IRolePermissionRepository rolePermissionRepository, ProvenanceDbContext dbContext)
        {
            _permissionRepository = permissionRepository;
            _logger = logger;
            _mapper = mapper;
            _rolePermissionRepository = rolePermissionRepository;
            _dbContext = dbContext;
        }
        public async Task<ApiResult> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var role = await _rolePermissionRepository.GetAsync(x => x.PermissionId == request.PermissionId && !x.IsDeleted);
                if (role != null)
                {
                    return ApiResult.Failure("此权限有角色关联，不能删除");
                }
                var obj = await _permissionRepository.GetAsync(x => x.PermissionId == request.PermissionId);
                //实体状态会设置为deleted
                _dbContext.Set<Permission>().Remove(obj);
                //经过EntityAuditInterceptor拦截器，修改实体状态为modified
                await _dbContext.SaveChangesAsync();
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting permission" + ex.Message);
                return ApiResult.Failure("Error deleting permission" + ex.Message);
            }
        }
    }
}
